const toolBar = getEl('.tool-bar'),
  textArea = getEl('#add-blog > textarea'),
  imageModalWrap = getEl('.image-modal-wrap'),
  html5ModalWrap = getEl('.html5-modal-wrap'),
  saveModalWrap = getEl('.save-modal-wrap');

toolBar.addEventListener('click', (event) => {
  let className;

  try {
    className = event.target.className.split(' ')[1].split('-')[1];
  } catch (err) {
    className = '';
  }

  if (className) {
    switch (className) {
      case 'eraser':
        textArea.value = '';
        break;

      case 'image':
        toggleClassName(imageModalWrap, 'modal-wrap-show');
        break;

      case 'html5':
        toggleClassName(html5ModalWrap, 'modal-wrap-show');
        break;

      case 'save':
        toggleClassName(saveModalWrap, 'modal-wrap-show');
      default:
      // do nothing
    }
  }
});

// ctrl + s
textArea.onkeydown = (e) => {
  let currKey = 0, _self = textArea;
  e = e || event || window.event;
  currKey = e.keyCode || e.which || e.charCode;
  if (currKey === 83 && (e.ctrlKey || e.metaKey)) {
    e.preventDefault();
    // show saveModalWrap
    toggleClassName(saveModalWrap, 'modal-wrap-show');
  } else if (currKey === 9) {
    e.preventDefault();
    const start = _self.selectionStart,
      end = _self.selectionEnd;
    _self.value = _self.value.substring(0, start) + '\t' + _self.value.substring(end);
    // put caret at right position again
    _self.selectionEnd = start + 1;
  }
}

// esc
document.onkeydown = (e) => {
  const _self = saveModalWrap;
  e = e || event || window.event;
  currKey = e.keyCode || e.which || e.charCode;
  if (currKey === 27) {
    e.preventDefault();
    hasClassName(saveModalWrap, 'modal-wrap-show')
      ? toggleClassName(saveModalWrap, 'modal-wrap-show')
      : null;
  }
}

// upload img
imageModalWrap.addEventListener('click', (event) => {
  switch (event.target.getAttribute('date-fn')) {
    case 'close-btn':
      toggleClassName(imageModalWrap, 'modal-wrap-show');
      break;
    case 'submit-btn':
      // 没有选择图片
      const imgFile = getEl('.img-file-input').files[0]
      if (imgFile) {
        const formData = new FormData()
        formData.append('file', imgFile)
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
              // 返回的链接
              textArea.value += `![](${xhr.responseText})`
              toggleClassName(imageModalWrap, 'modal-wrap-show')
            }
          }
        }
        xhr.open('POST', '/admin/upload_file', true)
        xhr.send(formData)
      } else {
        // post 图片
        alert('select image');
      }
      break;
    default:
      //nothing
      break;
  }
});

// upload *.html
html5ModalWrap.addEventListener('click', (event) => {
  switch (event.target.getAttribute('date-fn')) {
    case 'close-btn':
      toggleClassName(html5ModalWrap, 'modal-wrap-show');
      break;
    case 'submit-btn':
      // 没有选择图片
      if (!(titleInput.value && categoryInput.value && textArea.value)) {

      } else {
        // post 图片
      }
      break;
    default:
      //nothing
      break;
  }
});

// upload *.html
html5ModalWrap.addEventListener('click', (event) => {
  switch (event.target.getAttribute('date-fn')) {
    case 'close-btn':
      toggleClassName(html5ModalWrap, 'modal-wrap-show');
      break;
    case 'submit-btn':
      // 没有选择文件
      const imgFile = getEl('.html-file-input').files[0]
      if (imgFile) {
        const formData = new FormData()
        formData.append('file', imgFile)
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
              // 返回的链接
              textArea.value += `[](${xhr.responseText})`
              toggleClassName(html5ModalWrap, 'modal-wrap-show')
            }
          }
        }
        xhr.open('POST', '/admin/upload_file', true)
        xhr.send(formData)
      } else {
        alert('select html file');
      }
      break;
    default:
      //nothing
      break;
  }
});

/* submit to server */
const md = new markdownit({ html: true, breaks: true }),
  form = getEl('.save-modal-form'),
  titleInput = getEl(".save-modal-form > label > input[name='title']"),
  categoryInput = getEl(".save-modal-form > label > input[name='category']"),
  saveModal = getEl('.save-wrap-modal > .modal'),
  markdownContent = getEl(".save-modal-form > textarea[name='markdown-content']"),
  htmlContent = getEl(".save-modal-form > textarea[name='html-content']");

saveModalWrap.addEventListener('click', (event) => {
  switch (event.target.getAttribute('date-fn')) {
    case 'close-btn':
      toggleClassName(saveModalWrap, 'modal-wrap-show');
      break;
    case 'submit-btn':
      if (!(titleInput.value && categoryInput.value && textArea.value)) {
        toggleClassName(saveModalWrap, 'modal-wrap-show');
        alert('complete content');
      } else {
        markdownContent.value = textArea.value;
        htmlContent.value = md.render(textArea.value);
        console.log(1)
        form.submit();
      }
      break;
    default:
      break;
  }
});

const categoryBox = getEl('.category-container');
categoryBox.addEventListener('click', (event) => {
  const target = event.target;
  if (target.tagName.toLowerCase() === 'span') {
    categoryInput.value = target.innerText;
  }
});